import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Cookies from 'js-cookie'
import Vue from 'vue'

NProgress.configure({ showSpinner: false }) // NProgress Configuration
// no redirect whitelist
const whiteList = [
  '/login',
  '/frame',
  '/dashboard',
  '/frame/dashboard',
  '/frame/attendance/summary',
  '/frame/attendance/info-all',
  '/frame/attendance/info-dept',
  '/frame/attendance/info-person',
  '/frame/attendance/appeal',
  '/frame/leave/leave-all',
  '/frame/leave/leave-dept',
  '/frame/leave/leave-person',
  '/frame/travel/travel-all',
  '/frame/travel/travel-dept',
  '/frame/travel/travel-person',
  '/frame/travel/travel-change'
]

router.beforeEach(async(to, from, next) => {
  await Vue.prototype.loginUser()
  try {
    console.log('from:' + JSON.stringify(from))
    console.log('to:' + JSON.stringify(to))
  } catch (e) {
    console.log(e)
  }

  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken()

  // 设置头信息Authorization与sysCode
  try {
    const Authorization = to.query.Authorization || Cookies.get('Authorization')
    const sysCode = to.query.sysCode || Cookies.get('sysCode')
    if (Authorization && Authorization !== '') {
      Cookies.set('Authorization', Authorization)
    }
    if (sysCode && sysCode !== '' && sysCode !== 'undefined') {
      Cookies.set('sysCode', sysCode)
    }
  } catch (e) {
    console.log('set header exception:' + e)
  }

  // 获得参数传递
  const toName = to.name

  // 审批传参
  if (toName === 'approvalTravel' || toName === 'approvalAppeal' || toName === 'approvalLeave') {
    console.log('permission 审批传参')
    try {
      const instanceId = to.query.instanceId
      const taskId = to.query.taskId
      localStorage.setItem('processInstID', instanceId)
      localStorage.setItem('taskId', taskId)
    } catch (e) {
      console.log('set param exception:' + e)
    }
  }

  // 范围页面传参 all
  if (toName === 'leave-all' || toName === 'travel-all' || toName === 'info-all') {
    try {
      localStorage.setItem('queryRange', 'all')
    } catch (e) {
      console.log('set param exception:' + e)
    }
  }

  // 范围页面传参 dept
  if (toName === 'leave-dept' || toName === 'travel-dept' || toName === 'info-dept') {
    try {
      localStorage.setItem('queryRange', 'dept')
    } catch (e) {
      console.log('set param exception:' + e)
    }
  }

  // 范围页面传参 person
  if (toName === 'leave-person' || toName === 'travel-person' || toName === 'info-person') {
    try {
      localStorage.setItem('queryRange', 'person')
    } catch (e) {
      console.log('set param exception:' + e)
    }
  }

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')

          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

          // dynamically add accessible routes
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      console.log('in the free login whitelist, go directly')
      next()
    } else {
      console.log('other pages that do not have permission to access are redirected to the login page.')
      next()
      // next(`/login?redirect=${to.path}`)
      // NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
